import "./index.css";
import { defineComponent, ref, onMounted, nextTick, onUnmounted } from "vue";
import { PxTooltip, PxScrollbar } from "px-ui";
const props = {
  content: {
    type: String,
    default: ""
  },
  style: {
    type: Object,
    default: null
  }
};

export default defineComponent({
  name: "ReTextTooltip",
  props,
  setup(props) {
    const disabled = ref<boolean>(true);
    const ReTextTooltipRef = ref<HTMLElement | null>(null);

    const init = () => {
      if (ReTextTooltipRef.value) {
        disabled.value = ReTextTooltipRef.value.clientWidth >= ReTextTooltipRef.value.scrollWidth;
      }
    };

    // 监听目标元素是否在视窗内
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          init();
        }
      });
    });

    onMounted(async () => {
      await nextTick();
      observer.observe(ReTextTooltipRef.value);
      init();
    });

    onUnmounted(() => {
      observer.disconnect();
    });

    return () => (
      <PxTooltip
        disabled={disabled.value}
        vSlots={{
          content: () => (
            <PxScrollbar maxHeight={"300px"} style={{ maxWidth: "200px", maxHeight: "300px" }}>
              <div class="re-text-tooltip-content">{props.content}</div>
            </PxScrollbar>
          )
        }}
      >
        <div ref={ReTextTooltipRef} class="re-text-tooltip-text" style={{ ...props.style }}>
          {props.content || "--"}
        </div>
      </PxTooltip>
    );
  }
});
